package com.usian.admin.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.UserLoginService;
import com.usian.common.exception.CatchCustomException;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.common.BCrypt;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserLoginServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements UserLoginService {


    @Override
    public ResponseResult login(AdUserDto dto) {
        // 判断参数
        if(dto==null){
            CatchCustomException.catchs(20003,"参数有误");
        }
        if(StringUtils.isEmpty(dto.getName())||StringUtils.isEmpty(dto.getPassword())){
            CatchCustomException.catchs(20003,"用户名或密码为空");
        }
        // 判断登录
        AdUser adUser =  this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName,dto.getName()));
        if(adUser==null){
            CatchCustomException.catchs(20003,"用户名有误！");
        }
        if(adUser.getStatus()!=9){
            CatchCustomException.catchs(20003,"账号异常！");
        }
        // 通过bcypt
        if(!BCrypt.checkpw(dto.getPassword(),adUser.getPassword())){
            //失败
            CatchCustomException.catchs(20003,"密码有误！");
        }
        // 修改最后登录时间
        adUser.setLoginTime(new Date());
        updateByuId(adUser);
        // 签发令牌
        String token =  AppJwtUtil.getToken(Long.parseLong(adUser.getId()+""));
        Map<String,Object> resultMap = new HashMap<>();
        adUser.setPassword("");
        resultMap.put("user",adUser);
        resultMap.put("token",token);
        return ResponseResult.okResult(resultMap);
    }

    @Override
    public ResponseResult find(Integer id) {
        if (id==null){
            CatchCustomException.catchs(20003,"参数有误");
        }
        AdUser adUser = this.getById(id);
        return ResponseResult.okResult(adUser);
    }

    @Transactional
    public void updateByuId(AdUser adUser){
        this.saveOrUpdate(adUser);
    }
}
